﻿#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketNotification.h"
#include "json/json.h"
#include "Poco/NObserver.h"
// for timer
#include <iostream>
#include "event_loop.h"
// for log
#include "ZsLog.h"
//for http
#include <iostream>
#include "Poco/URI.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/StreamCopier.h"
#include "Poco/Path.h"
#include "Poco/Exception.h"
// for libcurl http
#include <curl/curl.h>
// poco https

using namespace Poco;
using namespace Poco::Net;
using namespace std;

size_t write_callback(char *ptr, size_t size, size_t nmemb, std::string *data)
{
    data->append(ptr, size * nmemb);
    return size * nmemb;
}

#if 1
void runLibCurl()
{
    CURL *curl;
    CURLcode res;
    std::string readBuffer;
    curl_global_init(CURL_GLOBAL_DEFAULT); // 初始化 libcurl
    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, "https://searchplugin.csdn.net/api/v1/ip/get");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
        {
            cerr << "Failed to get IP address: " << curl_easy_strerror(res) << endl;
        }
        else
        {
            cout << "Your IP address is: " << readBuffer << endl;
        }
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();

}
#endif


std::string gen_heartbeat_data()
{
    // 创建 JSON 对象
    Json::Value root;

    // 添加字段和值
    root["clientId"] = "ZgAf7cT8IMKiYrCgIMKitAkvNeIvyQvY";
    root["cmd"] = "heartbeat";
    root["opt"] = "request";
    root["affair"] = 0;
    root["time_interval"] = 5;

    // 将 JSON 对象转换为字符串
    Json::StreamWriterBuilder builder;
    return Json::writeString(builder, root) + "%AsJsonE%";
}


int main(int argc, char* argv[])
{
    //测试https连接
    runLibCurl();
    //tcp连接
    zs::SetLogPath("");
    LOG_INFO << "test log output";
    std::unique_ptr<zs::CEventLoop> event_loop = std::make_unique<zs::CEventLoop>();
    zs::CTcpConn::get_instance()->set_event_loop(event_loop.get());
    zs::CTcpConn::get_instance()->connect("8.138.135.101", 7208);
    event_loop->register_timer_event(1000, gen_heartbeat_data);
    event_loop->run();
    return 0;
}
